using Microsoft.EntityFrameworkCore;
using MediPlatform.Domain.Order;
using MediPlatform.Infeartructure;
using BCrypt.Net;

namespace MediPlatform.Read.Api.Services
{
    /// <summary>
    /// 退款申请数据初始化器
    /// </summary>
    public class RefundApplicationDataInitializer
    {
        private readonly MyDbContext _context;

        public RefundApplicationDataInitializer(MyDbContext context)
        {
            _context = context;
        }

        /// <summary>
        /// 初始化退款申请测试数据
        /// </summary>
        public async Task InitializeAsync()
        {
            // 检查是否已有数据
            if (await _context.RefundApplication.AnyAsync())
            {
                return; // 已有数据，不重复初始化
            }

            // 首先创建用户数据
            await CreateTestUsersAsync();

            var refundApplications = new List<RefundApplication>();
            var refundLogs = new List<RefundLog>();

            // 创建测试数据
            for (int i = 1; i <= 100; i++)
            {
                var application = new RefundApplication
                {
                    ApplicationNo = $"RF{DateTime.Now:yyyyMMdd}{i:D4}",
                    OrderId = i,
                    UserId = i,
                    Amount = 200.00m,
                    Status = GetRandomStatus(),
                    ApplyTime = DateTime.Now.AddDays(-i),
                    ProcessTime = GetRandomProcessTime(i),
                    ProcessorId = 1,
                    Remark = GetRandomRemark(i),
                    RefundChannel = "original",
                    RefundType = GetRandomRefundType(),
                    ExtraInfo = GetRandomSource(),
                    CreatedAt = DateTime.Now.AddDays(-i),
                    UpdatedAt = DateTime.Now.AddDays(-i)
                };

                refundApplications.Add(application);

                // 创建对应的退款日志
                var log = new RefundLog
                {
                    ApplicationId = i,
                    Status = application.Status,
                    OperatorId = 1,
                    OperateTime = application.ProcessTime ?? application.ApplyTime,
                    Remark = application.Remark,
                    CreatedAt = application.CreatedAt
                };

                refundLogs.Add(log);
            }

            // 批量插入数据
            await _context.RefundApplication.AddRangeAsync(refundApplications);
            await _context.RefundLog.AddRangeAsync(refundLogs);
            await _context.SaveChangesAsync();
        }

        /// <summary>
        /// 创建测试用户数据
        /// </summary>
        private async Task CreateTestUsersAsync()
        {
            // 检查是否已有足够的用户数据
            var existingUserCount = await _context.User.CountAsync();
            if (existingUserCount >= 100)
            {
                return; // 已有足够的用户数据
            }

            var users = new List<MediPlatform.Domain.Order.User>();

            // 创建100个测试用户
            for (int i = 1; i <= 100; i++)
            {
                var user = new MediPlatform.Domain.Order.User
                {
                    UserId = $"U{DateTime.Now:yyyyMMdd}{i:D4}",
                    Username = $"user{i}",
                    Email = $"user{i}@test.com",
                    PhoneNumber = $"188{i:D8}", // 生成手机号：18800000001, 18800000002, ...
                    PasswordHash = BCrypt.Net.BCrypt.HashPassword("123456", BCrypt.Net.BCrypt.GenerateSalt(12)),
                    Role = "patient",
                    CreatedAt = DateTime.Now.AddDays(-i),
                    UpdatedAt = DateTime.Now.AddDays(-i)
                };

                users.Add(user);
            }

            await _context.User.AddRangeAsync(users);
            await _context.SaveChangesAsync();
        }

        /// <summary>
        /// 获取随机状态
        /// </summary>
        /// <returns>状态值</returns>
        private static int GetRandomStatus()
        {
            var random = new Random();
            var statuses = new[] { 0, 1, 2 }; // 待处理、已处理、已拒绝
            return statuses[random.Next(statuses.Length)];
        }

        /// <summary>
        /// 获取随机处理时间
        /// </summary>
        /// <param name="index">索引</param>
        /// <returns>处理时间</returns>
        private static DateTime? GetRandomProcessTime(int index)
        {
            var random = new Random(index);
            // 70%的概率有处理时间
            if (random.Next(100) < 70)
            {
                return DateTime.Now.AddDays(-index).AddHours(random.Next(1, 24));
            }
            return null;
        }

        /// <summary>
        /// 获取随机备注
        /// </summary>
        /// <param name="index">索引</param>
        /// <returns>备注</returns>
        private static string GetRandomRemark(int index)
        {
            var random = new Random(index);
            var remarks = new[]
            {
                "用户主动申请退款",
                "服务未按时完成",
                "用户取消订单",
                "系统自动退款",
                "客服处理退款",
                "订单异常退款"
            };
            return remarks[random.Next(remarks.Length)];
        }

        /// <summary>
        /// 获取随机退款类型
        /// </summary>
        /// <returns>退款类型</returns>
        private static string GetRandomRefundType()
        {
            var random = new Random();
            var types = new[] { "cancel_order", "return_goods", "others" };
            return types[random.Next(types.Length)];
        }

        /// <summary>
        /// 获取随机来源
        /// </summary>
        /// <returns>来源</returns>
        private static string GetRandomSource()
        {
            var random = new Random();
            var sources = new[]
            {
                "挂号预约",
                "图文问诊",
                "视频问诊",
                "电话问诊",
                "药品订单",
                "检查预约"
            };
            return sources[random.Next(sources.Length)];
        }
    }
} 